var express=require('express');
var app =express();
var mysql = require('mysql');
var http=require('http');
var bodParser = require('body-parser');
var mysqlConnection=require('./mysqlConnection.js')   
var util = require('./utils.js');
// var fs = require("fs");
// var nodeMailer = require('nodemailer');
var localhost = 'localhost';
var loginStatus = 0;
var token = undefined;
var blogs = [];
var blogsinf = {
	prepage : 5,
	total : 0,
	page : 0,
};
var hideblogs = [];
var hideblogsinf = {
	prepage : 5,
	total : 0,
	page : 0,
};

app.use(require('cors')());
	//设置跨域访问
	app.all('*', function(req, res, next) {
	   res.header("Access-Control-Allow-Origin", "*");
	   // res.header("Access-Control-Allow-Headers", "X-Requested-With");
	   res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
	   res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
	   res.header("Access-Control-Allow-Credentials",true);
	   res.header("X-Powered-By",' 3.2.1');
	   res.header("Content-Type", "application/json;charset=utf-8");
	   next();
	   //设置允许跨域的域名，*代表允许任意域名跨域
	   //允许的header类型
	   //跨域允许的请求方式 
	   if (req.method.toLowerCase() == 'options')
		   res.send(200);  //让options尝试请求快速结束
	   else
		   next();
	});
	// app.all('*', function(req, res, next) {
	//     res.header("Access-Control-Allow-Origin", "*");
	//     res.header("Access-Control-Allow-Headers", "X-Requested-With");
	//     res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
	//     res.header("X-Powered-By", ' 3.2.1')
	//     res.header("Content-Type", "application/json;charset=utf-8");
	//     next();
	// });

 	var result = {
        "status": "200",
        "message": "success",  
    }
	
	//获取所有展示的blog
	function getblogs(){
		//链接数据库 
		mysqlConnection.select('select * from t_blog where published = 1 ORDER BY is_top desc,create_time desc', results=>{
			blogs = results;
			blogsinf.total = blogs.length;
			blogsinf.page = Math.ceil(blogsinf.total/blogsinf.prepage);
		});
	}
	//获取所有不展示的blog
	function gethideblogs(){
		//链接数据库 
		mysqlConnection.select('select * from t_blog where published != 1 ORDER BY is_top desc,create_time desc', results=>{
			hideblogs = results;
			hideblogsinf.total = hideblogs.length;
			hideblogsinf.page = Math.ceil(hideblogsinf.total/hideblogsinf.prepage);
		});
	}
	getblogs();
	gethideblogs();
	
	//登录接口
	app.get('/login',function(req,res){
		res.status(200);
		result.data = "blogs";
	    // console.log(req.stack);
	    // console.log(req.body);
	    console.log(req.url);
	    console.log(req.query.account);
		let account = "admin",
			password = '123456',
			acc = req.query.account,
			pwd = req.query.pwd;
		if(account == acc && pwd == password){
			result.login = 1;
			loginStatus = 1;
			token = util.tokenGenerator();
			result.token = token;
			console.log('登录成功',loginStatus);
		}else{
			result.login = 0;
		}
		res.json(result);
	});
	
	//退出登录接口
	app.get('/logout',function(req,res){
		res.status(200);
		loginStatus = 0;
		token = undefined;
		console.log('已退出登录',loginStatus);
		res.json(result);
	});
	
	
	//检查登录状态
	app.get('/logcheck',function(req,res){
		res.status(200);
		result.username = undefined;
		if(token == req.query.token){
			result.username = 'admin';
			loginStatus = 1;
		}
		else{
			loginStatus = 0;
		}
		result.login = loginStatus;
		console.log('登录状态：',loginStatus);
		res.json(result);
	});
	//保存博客
	app.get('/saveblog',async function(req,res){
		console.log('------------saveblog-------------------');
		res.status(200);
		if(token != req.query.token){
			result.result = false;
			result.message = "插入失败，token不符合";
			console.log("req.query.token:",req.query.token,"token:",token);
			console.log("saveblog插入失败，token不符合")
		}else{
			let nowtime = util.dateFilter(new Date()),
				title = req.query.title,
				content = req.query.content,
				html_content = req.query.html_content,
				description = req.query.description;
			let  sql = 'insert into t_blog(title,content,html_content,description,create_time,update_time,published) values(\'' + title + '\' , \'' + content +'\' , \'' + html_content + '\' , \'' + description +'\', \'' + nowtime +'\', \'' + nowtime +'\',1)';
			//链接数据库
			mysqlConnection.select(sql, results=>{
				// result.data = results;
				getblogs();
				console.log('------------getblogs-------------------');
			});
		}
	    res.json(result);
	});
	//查询所有博客
	app.get('/getblogs',async function(req,res){
		res.status(200);
		console.log("req.query.token:",req.query.token,"token:",token);
		getblogs();
		result.data = blogs;
		result.blogsinf = blogsinf;
		res.json(result);
	});
	//查询所有不展示的博客
	app.get('/gethideblogs',async function(req,res){
		res.status(200);
		console.log("req.query.token:",req.query.token,"token:",token);
		gethideblogs();
		result.data = hideblogs;
		result.blogsinf = blogsinf;
		res.json(result);
	});
	//通过id查询博客详情
	app.get('/getblogbyid',async function(req,res){
		res.status(200);
		console.log("req.query.token:",req.query.token,"token:",token);
		let  sql = 'select * from t_blog where id = \'' + req.query.id + '\'';
		//链接数据库
		mysqlConnection.select(sql, results=>{
			result.blog = results;
		});
		res.json(result);
	});
	
	//通过页码查询博客
	app.get('/getblogbypage',async function(req,res){
		getblogs();
		res.status(200);
		console.log("getblogbypage");
		console.log("req.query.token:",req.query.token,"token:",token,"page:",req.query.page);
		//链接数据库
		// let showblogs = [... blogs];
		let page = req.query.page;
		let flag = 1;
		if(page == 1) flag = 0;
		// showblogs = showblogs.splice((page-1) * blogsinf.prepage,page * blogsinf.prepage);
		let showblogs = blogs.slice((page-1) * blogsinf.prepage,page * blogsinf.prepage);
		result.data = showblogs;
		result.blogsinf = blogsinf;
		res.json(result);
	});
	
	//博客置顶
	app.get('/blogtotop',async function(req,res){
		res.status(200);
		console.log("blogtotop");
		console.log("req.query.token:",req.query.token,"token:",token,"id:",req.query.id);
		for(let i = 0; i < blogs.length; i++){
			if(blogs[i].id == req.query.id){
				blogs[i].is_top = 1;
				break;
			}
		}
		//链接数据库
		let  sql = 'update t_blog set is_top = 1 where id = \'' + req.query.id + '\'';
		mysqlConnection.select(sql, results=>{
			result.data = results;
			getblogs();
		});
		res.json(result);
	});
	
	//博客取消置顶
	app.get('/blogcanceltop',async function(req,res){
		res.status(200);
		console.log("blogcanceltop");
		console.log("req.query.token:",req.query.token,"token:",token,"id:",req.query.id);
		for(let i = 0; i < blogs.length; i++){
			if(blogs[i].id == req.query.id){
				blogs[i].is_top = 0;
				break;
			}
		}
		//链接数据库
		let  sql = 'update t_blog set is_top = 0 where id = \'' + req.query.id + '\'';
		mysqlConnection.select(sql, results=>{
			result.data = results;
			getblogs();
		});
		res.json(result);
	});
	
	//删除博客
	app.get('/removeblog',async function(req,res){
		res.status(200);
		console.log("removeblog");
		console.log("req.query.token:",req.query.token,"token:",token,"id:",req.query.id);
		//链接数据库
		let  sql = 'update t_blog set published = 0 where id = \'' + req.query.id + '\'';
		mysqlConnection.select(sql, results=>{
			result.data = results;
			getblogs();
		});
		res.json(result);
	});
	//编辑博客
	app.get('/editblog',async function(req,res){
		console.log('------------editblog-------------------',req,res);
		res.status(200);
		result.result = true;
		if(token != req.query.token){
			result.result = false;
			result.message = "插入失败，token不符合";
			console.log("req.query.token:",req.query.token,"token:",token);
			console.log("saveblog插入失败，token不符合")
		}else{
			let nowtime = util.dateFilter(new Date()),
				title = req.query.title,
				content = req.query.content,
				html_content = req.query.html_content,
				description = req.query.description;
			let  sql = 'update t_blog set title = \'' + title + '\',description = \'' + description + '\',content = \'' + content  + '\',html_content = \'' + html_content + '\',update_time = \'' + nowtime + '\' where id = \'' + req.query.id + '\'';
			//链接数据库
			mysqlConnection.select(sql, results=>{
				// result.data = results;
				getblogs();
				console.log('------------getblogs-------------------');
			});
		}
	    res.json(result);
	});
	
	//浏览量添加
	app.get('/addview',async function(req,res){
		res.status(200);
		console.log("req.query.token:",req.query.token,"token:",token,"id:",req.query.id);
		let id = req.query.id;
		
		let  sql = 'UPDATE t_blog SET views = (SELECT ub.views FROM (SELECT (ua.views+1) views FROM t_blog ua WHERE ua.id = \'' + id + '\')ub) WHERE id = \'' + id + '\' ';
		//链接数据库
		console.log("addview",sql);
		mysqlConnection.select(sql, results=>{
			// result.data = results;
			getblogs();
			console.log('------------addview-------------------');
		});
		res.json(result);
	});
	
	//获取页码信息
	app.get('/getpageinf',async function(req,res){
		res.status(200);
		console.log("getpageinf");
		console.log("req.query.token:",req.query.token,"token:",token,"page:",req.query.page);
		//链接数据库
		result.blogsinf = blogsinf;
		res.json(result);
	});
	//配置服务端口
	var server = app.listen(3000, function () {
	var host = server.address().address;
	var port = server.address().port;
	    console.log('Example app listening at http://%s:%s', host, port);
	})